<?php
class ModelCustomerCustomer extends Model {

	public function editCustomer($customer_id, $customer_grade_id = 0, $status = 1) {
		$this->db->query("UPDATE " . DB_PREFIX . "customer SET customer_grade_id = '" . (int)$customer_grade_id . 
			"', `status` = '" . (int)$status . "' WHERE customer_id = '" . (int)$customer_id . "'");
	}
	
	public function getCustomer($customer_id) {
		$query = $this->db->query("SELECT c.customer_id, c.firstname, c.lastname, c.sex, c.email, " . 
			"c.phone, c.fax, c.newsletter, c.customer_grade_id, c.`point`, c.language_id, INET_NTOA(c.register_ip) register_ip, c.status, " . 
			"FROM_UNIXTIME(c.date_added, '%Y-%m-%d') date_added, l.`name` language_name, l.`code` language_code FROM " . 
			DB_PREFIX . "customer c LEFT JOIN `" . 
			DB_PREFIX . "language` l ON c.language_id = l.language_id WHERE customer_id = '" . (int)$customer_id . "'");
		return $query->row;
	}
			
	public function getCustomers($data = array()) {
		$sql = "SELECT c.customer_id, CONCAT(c.firstname, ' ', c.lastname) name, c.email, c.newsletter, c.point, " . 
			"FROM_UNIXTIME(c.date_added, '%Y-%m-%d') date_added, cgd.display_name grade_name FROM " . 
			DB_PREFIX . "customer c LEFT JOIN " . 
			DB_PREFIX . "customer_grade_description cgd ON c.customer_grade_id = cgd.customer_grade_id AND cgd.language_id = '" . 
			(int)$this->config->get('config_language_id') . "' WHERE c.`status` = '1'";

		if (isset($data['filter_name'])) {
			$sql .= " AND LCASE(CONCAT(c.firstname, ' ', c.lastname)) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "%'";
		}
		if (isset($data['filter_email'])) {
			$sql .= " AND LCASE(c.email) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_email'])) . "%'";
		}
		if (isset($data['filter_newsletter'])) {
			$sql .= " AND c.newsletter = '" . (int)$data['filter_newsletter'] . "'";
		}	
		if (isset($data['filter_customer_grade_id'])) {
			$sql .= " AND c.customer_grade_id = '" . (int)$data['filter_customer_grade_id'] . "'";
		}
		
		$sort_data = array(
			'name',
			'c.email',
			'c.customer_grade_id'
		);	
			
		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];	
		} else {
			$sql .= " ORDER BY name";	
		}
			
		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}
		
		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}			
			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}	
			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}		
		
		$query = $this->db->query($sql);
		
		return $query->rows;	
	}
	
	public function getTotalCustomers($data = array()) {
      	$sql = "SELECT COUNT(*) AS total FROM " . 
			DB_PREFIX . "customer c LEFT JOIN " . 
			DB_PREFIX . "customer_grade_description cgd ON c.customer_grade_id = cgd.customer_grade_id AND cgd.language_id = '" . 
			(int)$this->config->get('config_language_id') . "' WHERE c.`status` = '1'";

		if (isset($data['filter_name'])) {
			$sql .= " AND LCASE(CONCAT(c.firstname, ' ', c.lastname)) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "%'";
		}
		if (isset($data['filter_email'])) {
			$sql .= " AND LCASE(c.email) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_email'])) . "%'";
		}
		if (isset($data['filter_newsletter'])) {
			$sql .= " AND c.newsletter = '" . (int)$data['filter_newsletter'] . "'";
		}	
		if (isset($data['filter_customer_grade_id'])) {
			$sql .= " AND c.customer_grade_id = '" . (int)$data['filter_customer_grade_id'] . "'";
		}
		
		$query = $this->db->query($sql);
				
		return $query->row['total'];
	}
	
	public function getAddresses($customer_id) {
		$address_data = array();
		$query = $this->db->query("SELECT a.*, cd.display_name country_name, czd.display_name zone_name, ccd.display_name city_name FROM " . 
			DB_PREFIX . "customer_address a LEFT JOIN " .  
			DB_PREFIX . "country_description cd ON a.country_id = cd.country_id AND cd.language_id = '" . 
			(int)$this->config->get('config_language_id') . "' LEFT JOIN " . 
			DB_PREFIX . "country_zone_description czd ON a.country_zone_id = czd.country_zone_id AND czd.language_id = '" . 
			(int)$this->config->get('config_language_id') . "' LEFT JOIN " . 
			DB_PREFIX . "country_city_description ccd ON a.country_city_id = ccd.country_city_id AND ccd.language_id = '" . 
			(int)$this->config->get('config_language_id') . 
			"' WHERE a.customer_id = '" . (int)$customer_id . 
			"' ORDER BY a.is_default DESC, a.customer_address_id DESC");  
		return $query->rows;
	}
	
	public function countIpsByCustomerId($customer_id) {
		$query = $this->db->query("SELECT ip, FROM_UNIXTIME(MAX(date_added), '%Y-%m-%d') last_login_date, COUNT(ip) login_num FROM " . 
			DB_PREFIX . "customer_login_ip WHERE customer_id = '" . (int)$customer_id . 
			"' GROUP BY ip ORDER BY MAX(date_added) DESC, COUNT(ip) DESC LIMIT 50");
		return $query->rows;
	}
	
	public function addBlacklist($customer_id, $reason) {
		$this->db->query("INSERT INTO " . DB_PREFIX . "customer_blacklist SET customer_id = '" . (int)$customer_id . 
			"', reason = '" . $this->db->escape($reason) . "', date_added = UNIX_TIMESTAMP()");
	}
	
	public function customerAutoComplete($filter_email) {
		$sql = "SELECT c.customer_id, CONCAT(c.firstname, ' ', c.lastname) name, c.email, cgd.display_name grade_name FROM " . 
			DB_PREFIX . "customer c LEFT JOIN " . 
			DB_PREFIX . "customer_grade_description cgd ON c.customer_grade_id = cgd.customer_grade_id AND cgd.language_id = '" . 
			(int)$this->config->get('config_language_id') . "' WHERE c.`status` = '1'";

		$sql .= " AND LCASE(c.email) LIKE '" . $this->db->escape(utf8_strtolower($filter_email)) . "%'";
		
		$sql .= " ORDER BY c.email LIMIT 0, 50";
		
		$query = $this->db->query($sql);
		
		return $query->rows;	
	}
	
	
	
	
	
	
	
	public function approve($customer_id) {
		$customer_info = $this->getCustomer($customer_id);

		if ($customer_info) {
			$this->db->query("UPDATE " . DB_PREFIX . "customer SET approved = '1' WHERE customer_id = '" . (int)$customer_id . "'");

			$this->load->language('mail/customer');
			
			$store_name = $this->config->get('config_name');
			$store_url = HTTP_CATALOG . 'index.php?route=account/login';
	
			$message  = sprintf($this->language->get('text_approve_welcome'), $store_name) . "\n\n";
			$message .= $this->language->get('text_approve_login') . "\n";
			$message .= $store_url . "\n\n";
			$message .= $this->language->get('text_approve_services') . "\n\n";
			$message .= $this->language->get('text_approve_thanks') . "\n";
			$message .= $store_name;
	
			$mail = new Mail();
			$mail->protocol = $this->config->get('config_mail_protocol');
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->hostname = $this->config->get('config_smtp_host');
			$mail->username = $this->config->get('config_smtp_username');
			$mail->password = $this->config->get('config_smtp_password');
			$mail->port = $this->config->get('config_smtp_port');
			$mail->timeout = $this->config->get('config_smtp_timeout');							
			$mail->setTo($customer_info['email']);
			$mail->setFrom($this->config->get('config_email'));
			$mail->setSender($store_name);
			$mail->setSubject(html_entity_decode(sprintf($this->language->get('text_approve_subject'), $store_name), ENT_QUOTES, 'UTF-8'));
			$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
			$mail->send();
		}		
	}
		
	public function getAddress($customer_address_id) {
		$address_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer_address WHERE customer_address_id = '" . (int)$customer_address_id . "'");

		if ($address_query->num_rows) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$address_query->row['country_id'] . "'");
			
			if ($country_query->num_rows) {
				$country = $country_query->row['name'];
				$iso_code_2 = $country_query->row['iso_code_2'];
				$iso_code = $country_query->row['iso_code'];
			} else {
				$country = '';
				$iso_code_2 = '';
				$iso_code = '';
			}
			
			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$address_query->row['zone_id'] . "'");
			
			if ($zone_query->num_rows) {
				$zone = $zone_query->row['name'];
				$zone_code = $zone_query->row['code'];
			} else {
				$zone = '';
				$zone_code = '';
			}		
		
			return array(
				'address_id'     => $address_query->row['address_id'],
				'customer_id'    => $address_query->row['customer_id'],
				'firstname'      => $address_query->row['firstname'],
				'lastname'       => $address_query->row['lastname'],
				'company'        => $address_query->row['company'],
				'company_id'     => $address_query->row['company_id'],
				'tax_id'         => $address_query->row['tax_id'],
				'address_1'      => $address_query->row['address_1'],
				'address_2'      => $address_query->row['address_2'],
				'postcode'       => $address_query->row['postcode'],
				'city'           => $address_query->row['city'],
				'zone_id'        => $address_query->row['zone_id'],
				'zone'           => $zone,
				'zone_code'      => $zone_code,
				'country_id'     => $address_query->row['country_id'],
				'country'        => $country,	
				'iso_code_2'     => $iso_code_2,
				'iso_code_3'     => $iso_code_3,
				'address_format' => $address_format
			);
		}
	}

	public function getTotalCustomersAwaitingApproval() {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer WHERE status = '0' OR approved = '0'");

		return $query->row['total'];
	}
	
	public function getTotalAddressesByCustomerId($customer_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "address WHERE customer_id = '" . (int)$customer_id . "'");
		
		return $query->row['total'];
	}
	
	public function getTotalAddressesByCountryId($country_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "address WHERE country_id = '" . (int)$country_id . "'");
		
		return $query->row['total'];
	}	
	
	public function getTotalAddressesByZoneId($zone_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "address WHERE zone_id = '" . (int)$zone_id . "'");
		
		return $query->row['total'];
	}
	
	public function getTotalCustomersByCustomerGradeId($customer_grade_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer WHERE customer_grade_id = '" . (int)$customer_grade_id . "'");
		
		return $query->row['total'];
	}
	
	
		
	public function deleteBlacklist($ip) {
		$this->db->query("DELETE FROM `" . DB_PREFIX . "customer_ip_blacklist` WHERE `ip` = '" . $this->db->escape($ip) . "'");
	}
			
	public function getTotalBlacklistsByIp($ip) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "customer_ip_blacklist` WHERE `ip` = '" . $this->db->escape($ip) . "'");
				 
		return $query->row['total'];
	}	
}
?>